package cn.geminis.cloud.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Service;

/**
 * @author puddi
 */
@Service
public class LoginUserGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> ReactiveSecurityContextHolder.getContext()
                .map(SecurityContext::getAuthentication)
                .as(value -> value.flatMap(authentication -> {
                    var loginUser = authentication.getName();
                    var request = exchange.getRequest()
                            .mutate()
                            .header(HttpHeaders.AUTHORIZATION, loginUser)
                            .build();
                    var newExchange = exchange
                            .mutate()
                            .request(request)
                            .build();
                    return chain.filter(newExchange);
                }))
                .switchIfEmpty(chain.filter(exchange));
    }
}
